package cn.mrlong.base.ktnet.adapter

import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.TypeAdapter
import okhttp3.ResponseBody
import retrofit2.Converter

/**
 * 作者：BINGO
 * 时间：2021/04/25 17:35
 */
class MGsonResponseBodyConverter<T> internal constructor(
    private val gson: Gson,
    private val adapter: TypeAdapter<T>,
    private val baseBeanClazz: Class<T>
) : Converter<ResponseBody, T> {

    override fun convert(value: ResponseBody): T {
        var valueString: String? = null
        return try {
            valueString = value.string()
            adapter.fromJson(valueString)
        } catch (e: JsonSyntaxException) {
            try {
                gson.fromJson(valueString, baseBeanClazz)
            } catch (e1: JsonSyntaxException) {
                throw e1
            } catch (e2: ClassCastException) {
                throw e2
            }
        } finally {
            value.close()
        }
    }
}